<?php 
namespace Emos\Field;

use Emos\Common;
use Emos\Db;

class Date extends AbstractControl {
    public function __construct() {        
    }
    
    public function html() {
        $value = '';    
        if($v = $this->parseDbString($this->value)) {                            
            $value = "{$v['day']}.{$v['month']}.{$v['year']}";
        }
        
        return "<input type='text' class='datepicker' data-format='dd.mm.yy' name='{$this->htmlName}' value='".Common::plain($value)."' />";
    }
    
    public function update() {
        $newValue = $this->getPost();
        if($newValue === null) {
            return array($this->dbName => new Db\SqlExpression("NULL"));        
        }
        else {            
            if($v = $this->parseInputString($newValue)) {                 
                return array($this->dbName => "{$v['year']}-{$v['month']}-{$v['day']}");        
            }            
        }
    }  
    
    public function validate() {            
        if($v = $this->parseInputString($this->getPost())) {                            
            if(
                $v['day']   >= 1  &&  $v['day']   <= 31 &&
                $v['month'] >= 1  &&  $v['month'] <= 12 && 
                $v['year']  >= 1  &&  $v['year']  <= 9999
            ) {
                return; 
            }
        }       
        
        $this->error = true;                        
    }
    
    public function getDdlFields() {
        return array(
            $this->dbName => "DATE"
        );
    }   
    
    protected function parseDbString($str) {
        if(preg_match('/^ (?<year> \d+) \- (?<month> \d+) \- (?<day> \d+) /xui', $str, $m)) {                            
            return $m;
        }
        return null;
    }
    
    protected function parseInputString($str) {
        if(preg_match('/^ (?<day> \d+) \. (?<month> \d+) \. (?<year> \d+) $/xui', $str, $m)) {                            
            return $m;
        }
        return null;
    }   
    
    public function getFake() {                
        $y = date('Y') + rand(-3,3);
        $m = rand(1,12);
        $d = rand(1,28);
        
        return array(
            $this->dbName => "'{$y}-{$m}-{$d}'"
        );
    }  
}